package cn.gd.controller;

import cn.gd.pojo.Users;
import cn.gd.service.Login.LoginService;
import cn.gd.utils.EncryptionUtil;
import cn.gd.utils.LogUtils;
import cn.gd.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.NoSuchAlgorithmException;
import java.util.HashMap;


// @Api(tags = "后台登录管理")
@Slf4j
@CrossOrigin
@RestController
public class LoginController {
    @Autowired
    private LoginService loginService;
    private String username, password;


    @ResponseBody
    @RequestMapping(value = "/sys/login", method = RequestMethod.POST)
    public Result<Object> login(String username, String password) throws NoSuchAlgorithmException {
        this.username = username;
        this.password = EncryptionUtil.hashPassword(password);
        if (loginService.queryUserLogin(username, this.password)) {
            HashMap<String, Object> responseData = new HashMap<>();
            responseData.put("token","admin-token");
            return Result.ok(responseData);
        }
        return Result.error().message("登录失败或账户已冻结");
    }


    @GetMapping(value = "/sys/info")
    @ResponseBody
    public Result info() {
        Users users = loginService.getUsers(username, password);
        HashMap<String, Object> responseData = new HashMap<>();
        responseData.put("roles","admin");

        responseData.put("name",users.getUserName());
        // 头像
        responseData.put("avatar","https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
        responseData.put("users",users);
       LogUtils.userID = users.getUserID();
        return Result.ok(responseData);
    }

    @PostMapping("/sys/logout")
    public Result logOut() {
        return Result.ok();
    }

    @PutMapping("/user/updatePassword")
    public Result<Boolean> updatePassword(Integer userID, String newPassword) throws NoSuchAlgorithmException {
        String newPassword2 = EncryptionUtil.hashPassword(newPassword);
        return Result.ok(loginService.updatePassword(userID,newPassword2));
    }
}
